<template>
  <div class="analysis-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="chart-card">
          <div class="card-header">
            <span>商品销售数量分析</span>
          </div>
          <div class="chart-container">
            <div ref="barChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="mt-20">
      <el-col :span="24">
        <el-card class="chart-card">
          <div class="card-header">
            <span>商品销售占比分析</span>
          </div>
          <div class="chart-container">
            <div ref="pieChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import dayjs from 'dayjs';
import { ref, onMounted, nextTick } from 'vue'
import axios from '@/util/axios'
import * as echarts from 'echarts'

const chartData = ref([])
const barChartRef = ref(null)
const pieChartRef = ref(null)
let barChart = null
let pieChart = null

const initOrderList = async () => {
  // 计算 7 天前的日期
  const sevenDaysAgo = dayjs().subtract(7, 'day').startOf('day');
  // 格式化日期为字符串
  const sevenDaysAgoFormat = sevenDaysAgo.format('YYYY-MM-DD HH:mm:ss');
  const params = {
    payDate: sevenDaysAgoFormat
  };
  const res = await axios.post("admin/order/analysis", params);
  chartData.value = res.data.analysis;
  console.log(res.data.analysis);
  console.log(chartData.value);
  
  // 数据加载完成后初始化图表
  await nextTick();
  initCharts();
}

// 初始化图表
const initCharts = () => {
  initBarChart();
  initPieChart();
}

// 初始化柱状图
const initBarChart = () => {
  if (barChart) {
    barChart.dispose();
  }
  
  barChart = echarts.init(barChartRef.value);
  
  // 对数据进行排序（从多到少）
  const sortedData = [...chartData.value].sort((a, b) => b.count - a.count);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: sortedData.map(item => item.goodsName),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '销售数量'
    },
    series: [
      {
        name: '销售数量',
        type: 'bar',
        data: sortedData.map(item => item.count),
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  };
  
  barChart.setOption(option);
  
  // 响应式调整
  window.addEventListener('resize', () => {
    barChart.resize();
  });
}

// 初始化饼图
const initPieChart = () => {
  if (pieChart) {
    pieChart.dispose();
  }
  
  pieChart = echarts.init(pieChartRef.value);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      type: 'scroll',
      pageIconSize: 12,
      pageTextStyle: {
        color: '#666'
      }
    },
    series: [
      {
        name: '销售占比',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: chartData.value.map(item => ({
          value: item.count,
          name: item.goodsName
        }))
      }
    ]
  };
  
  pieChart.setOption(option);
  
  // 响应式调整
  window.addEventListener('resize', () => {
    pieChart.resize();
  });
}

onMounted(() => {
  initOrderList();
})
</script>

<style lang="scss" scoped>
.analysis-container {
  padding: 20px;
  
  .chart-card {
    margin-bottom: 20px;
    
    .card-header {
      font-size: 16px;
      color: #606266;
      margin-bottom: 15px;
      font-weight: bold;
    }
    
    .chart-container {
      .chart {
        height: 400px;
        width: 100%;
      }
    }
  }
  
  .mt-20 {
    margin-top: 20px;
  }
}
</style>